import axios from "@/request/request"
const state = {
  audioUrl: localStorage.getItem('audioUrl') || '',
  audioInfo: JSON.parse(localStorage.getItem('audioInfo')) || {},
  // 当前播放列表
  nowPlayList: []
}
const mutations = {
  updateAudioUrl(state, { url, audioInfo }) {
    state.audioUrl = url
    state.audioInfo = audioInfo
  },
  updateNowPlayList(state, list) {
    state.nowPlayList = list
  }
}
// 格式化歌曲毫秒数
function format(dt) {
  let m = parseInt(dt / 1000 / 60)
  let s = ((dt / 1000) % 60).toFixed(0)
  if (m < 10) {
    m = '0' + m
  }
  if (s < 10) {
    s = '0' + s
  }
  return m + ':' + s
}

const actions = {
  // 获取音乐url
  async getSongUrl({ commit }, row) {
    const { data: res } = await axios.get(`/song/url?id=${row.id}`)
    if (res.code == 200) {
      localStorage.setItem('audioUrl', res.data[0].url)
      localStorage.setItem('audioInfo', JSON.stringify(row))
      commit('updateAudioUrl', { url: res.data[0].url, audioInfo: row })
    }
  },
  // 获取专辑所有歌曲
  async getAlbumSongs({ commit }, id) {
    const { data: res } = await axios.get(`/album?id=${id}`)
    if (res.code == 200) {
      res.songs.forEach(item => {
        item.dt = format(item.dt)
      })
      commit('updateNowPlayList', res.songs)
    }
  },
  // 获取歌单所有歌曲
  async getPlaySongs({ commit }, id) {
    const { data: res } = await axios.get(`/playlist/track/all?id=${id}`)
    if (res.code == 200) {
      res.songs.forEach(item => {
        item.dt = format(item.dt)
      })
      commit('updateNowPlayList', res.songs)
    }
  },
  // 获取歌单所有歌曲(用户收藏列表点击时)
  async getPlayListSongs({ commit, dispatch }, id) {
    const { data: res } = await axios.get(`/playlist/track/all?id=${id}`)
    if (res.code == 200) {
      res.songs.forEach(item => {
        item.dt = format(item.dt)
      })
      dispatch('getSongUrl', res.songs[0])
      commit('updateNowPlayList', res.songs)
    }
  }
}
const getters = {
  playListLength(state) {
    return state.nowPlayList.length
  },
  firstId(state) {
    const a = state.nowPlayList || []
    const b = a[0] || {}
    return b.id
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}